package com.aat.dizena.service;

import com.aat.dizena.bean.User;
import com.aat.dizena.dao.UserDao;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.data.domain.Page;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Iterator;
import java.util.Optional;

@Service
public class UserService
{
    @Resource
    private UserDao dao;


    public void save(User s)
    {
        dao.save(s);
    }

    public void delete(Long id)
    {
        dao.deleteById(id);
    }

    public User findById(Long id)
    {
        Optional<User> res = dao.findById(id);
        return res.orElse(null);
    }

    public Iterator<User> findAll()
    {
        return dao.findAll().iterator();
    }

    public Page<User> search(String field, String value)
    {
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        queryBuilder.withQuery(QueryBuilders.matchQuery(field, value));
        return dao.search(queryBuilder.build());
    }

    public void init()
    {
        User m1 = new User(1L, "李白", "诗人,刺客,文学,西红柿");
        User m2 = new User(2L, "赵云", "将军,刺客,现金,番茄");
        User m3 = new User(3L, "韩信", "将军,刺客,钞票");
        save(m1);
        save(m2);
        save(m3);
    }

}
